package org.migsoft.id3lib;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.migsoft.id3lib.id3v1.ID3v1Tag;
import org.migsoft.id3lib.stringdecoders.EncodingDecoder;
import org.migsoft.id3lib.stringdecoders.UTF8Decoder;

public class Mp3File {
  private byte[] musicData;
  private File file;
  private ID3v1Tag id3v1Tag;
  private StringDecoder decoder;

  private Mp3File(File file, StringDecoder decoder) throws IOException, ID3Exception {
    super();
    this.file = file;
    this.decoder = decoder;
    musicData = new byte[(int) file.length()];
    
    final DataInputStream inputStream = new DataInputStream(new FileInputStream(file));
    inputStream.readFully(musicData);
    inputStream.close();

    detectID3v1Tag();
  }
  
  private Mp3File(File file, Mp3File otherFile) throws IOException, ID3Exception {
    super();
    this.file = file;
    musicData = new byte[otherFile.musicData.length];
    System.arraycopy(otherFile.musicData, 0, musicData, 0, musicData.length);
    id3v1Tag = new ID3v1Tag(otherFile.id3v1Tag);
    decoder = otherFile.decoder;
  }
  
  public ID3v1Tag getId3v1Tag() {
    return id3v1Tag;
  }



  private void detectID3v1Tag() throws ID3Exception {
    if(ID3v1Tag.isValidID3v1Tag(musicData)){
      byte[] musicData = new byte[this.musicData.length - 128];
      byte[] idv3 = new byte[128];
      System.arraycopy(this.musicData, 0, musicData, 0, musicData.length);
      System.arraycopy(this.musicData, this.musicData.length - 128, idv3, 0, 128);
      id3v1Tag = new ID3v1Tag(idv3, decoder);
    }
  }
  
  public void sync() throws IOException{
    FileOutputStream out = new FileOutputStream(file);
    out.write(musicData);
    if(id3v1Tag != null)
      out.write(id3v1Tag.getBytes());
  }
  
  
  
  public static void main(String[] args) throws IOException, ID3Exception {
    Mp3File file = new Mp3File(new File("/tmp/11111111112/01.mp3"), new EncodingDecoder("CP1251"));
    ID3v1Tag id3v1Tag = file.getId3v1Tag();
    if(id3v1Tag != null){
      System.out.println(id3v1Tag.getTitle());
      System.out.println(id3v1Tag.getArtist());
      System.out.println(id3v1Tag.getAlbum());
      System.out.println(id3v1Tag.getYear());
      System.out.println(id3v1Tag.getComment());
      System.out.println(id3v1Tag.getGenre().getTitle());
    }
    Mp3File file2 = new Mp3File(new File("/tmp/11111111112/02.mp3"), file);
    file2.sync();
  }
}
